<template>
  <el-card>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="角色名称" prop="rolename">
        <el-input type="text" v-model="ruleForm.rolename" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="menus">
        <el-tree
          :data="data"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="defaultProps"
          ref="menuTree"
        ></el-tree>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <!-- 1:正常 2:异常 -->
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
export default {
  data() {
    const menuValid = (rule, value, callback) => {
      // 如果this.$refs.menuTree.getCheckedkeys().length==0说明用户没有勾选树形控件
      if (this.$refs.menuTree.getCheckedKeys().length == 0) {
        return callback(new Error("请至少勾选一个权限节点"));
      }
      callback();
    };
    return {
      ruleForm: {
        rolename: "",
        menus: [],
        status: 1
      },
      rules: {
        rolename: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        menus: {
          validator: menuValid,
          trigger: "blur"
        },
        status: [{ required: true, message: "请输选择状态", trigger: "blur" }]
      },
      data: [],
      defaultProps: {
        children: "children",
        label: "title"
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 发请求, 提交角色信息
          this.ruleForm.menus = this.$refs.menuTree.getCheckedKeys().join(",");
          const res = await this.$http.post("/api/roleadd", this.ruleForm);
          if (res.code == 200) {
            this.$success("添加成功");
            // 重置表单
            this.$refs.menuTree.resetFields();
          } else {
            this.$error("添加失败");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 获取树形菜单
    async getMenuTree() {
      const res = await this.$http.get("/api/menulist?istree=1");
      if (res.code == 200) {
        this.data = res.list;
      }
    }
  },
  created() {
    this.getMenuTree();
  }
};
</script>
<style>
</style>